package com.waitingresult.demo.controller;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.waitingresult.demo.entity.Result;
import com.waitingresult.demo.entity.User;
import com.waitingresult.demo.mapper.UserMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * @Author: WangShuai
 * @CreateTime: 2023/5/17  17:59
 * @Description:
 * @Version: 1.0
 */
@RestController
@RequestMapping("user")
public class UserController {

    @Resource
    private UserMapper userMap;
    @Resource
    private RedisTemplate redisTemplate;

    @Bean
    public RedisTemplate redisTemplateInit() {
        //设置序列化Key的实例化对象
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        //设置序列化Value的实例化对象
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        return redisTemplate;
    }

    @GetMapping(value = "all", name = "查询所有")
    public Result selectAll() {
        return Result.success(userMap.selectList(null));
    }

    @GetMapping(value = "select/{id}", name = "查询所有")
    public Result selectById(@PathVariable("id") Integer id) {
        User user = userMap.selectById(id);
        redisTemplate.opsForValue().set("log:user:" + id, JSON.toJSONString(user));
        return Result.success(user);
    }

    @PostMapping(value = "update", name = "更新")
    public Result update(@RequestBody User user) {
        return Result.success(userMap.updateByEntity(user));
    }

    @PostMapping(value = "select", name = "查询所有")
    public Result select(@Validated @RequestBody User user) {
        return Result.success(userMap.selectList(Wrappers.lambdaQuery(user)));
    }

}
